package com.guocloud.medimind.config;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetriever;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetrieverOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.model.ApiKey;
import org.springframework.ai.rag.advisor.RetrievalAugmentationAdvisor;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
@Slf4j
class RagCloudAdvisorConfig {

    @Value("${aliYunAi.apiKey:sk-38af19cfa7144bfda25618b42cc9e586}")
    private String dashScopeApiKey;
    
    @Autowired
    private RestClient.Builder restClientBuilder;
    
    @Autowired
    private WebClient.Builder webClientBuilder;

    @Bean
    public Advisor loveAppRagCloudAdvisor() {
        log.info("初始化RAG知识库Advisor");
        
        // 检查API Key
        if (!StringUtils.hasText(dashScopeApiKey)) {
            log.warn("未配置DashScope API Key，使用默认值");
            dashScopeApiKey = "sk-38af19cfa7144bfda25618b42cc9e586";
        }
        
        // 创建ApiKey对象 - 使用匿名实现类
        ApiKey apiKey = new ApiKey() {
            @Override
            public String getValue() {
                return dashScopeApiKey;
            }
        };
        
        // 创建headers
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        
        // 创建错误处理器
        DefaultResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
        
        // 创建DashScopeApi实例
        DashScopeApi dashScopeApi = new DashScopeApi(
            "https://dashscope.aliyuncs.com",  // baseUrl
            apiKey,  // ApiKey对象
            headers,  // headers
            null,  // workSpaceId
            restClientBuilder,
            webClientBuilder,
            errorHandler  // responseErrorHandler
        );
        
        final String KNOWLEDGE_INDEX = "病历模板";
        log.info("使用知识库索引: {}", KNOWLEDGE_INDEX);
        
        DocumentRetriever documentRetriever = new DashScopeDocumentRetriever(dashScopeApi,
                DashScopeDocumentRetrieverOptions.builder()
                        .withIndexName(KNOWLEDGE_INDEX)
                        .build());
        return RetrievalAugmentationAdvisor.builder()
                .documentRetriever(documentRetriever)
                .build();
    }
}
